#include "DFRobot_PH_K10.h"
#include "Arduino.h"


//#define PHVALUEADDR 0x00    //the start address of the pH calibration parameters stored in the EEPROM



DFRobot_PH::DFRobot_PH()
{
    this->pHArrayIndex = 0;
    this->enable = false;
    this->valuePrev = 0;
    this->first = true;
    pHArray = (int *)malloc(sizeof(int)*20);
    if(pHArray) this->enable = true;
}

DFRobot_PH::~DFRobot_PH()
{
    this->pHArrayIndex = 0;
    this->valuePrev = 0;
    this->first = true;
    if(pHArray) free(pHArray);
    this->enable = false;
}

float DFRobot_PH::readPH(uint32_t pin)
{
    if(!this->pHArray || !this->enable) 
        return 0;
    int count = 1;
    if(this->first){
        count = 20;
        this->first = false;
    }
    for(int i= 0; i<count; i++){
        pHArray[this->pHArrayIndex] = analogRead(pin);
        this->pHArrayIndex = (this->pHArrayIndex + 1) % 20;
        delay(20);
    }
    float offset1;
    float k;
    aref = 3.3;
    offset1=16;
    k=-6;
    
    float voltage = avergeArray() * aref / map;
    return k * voltage + offset1; 
}

float DFRobot_PH::avergeArray()
{
    if(!this->pHArray || !this->enable) 
        return 0;
    int i;
    int max,min;
    double avg;
    long amount=0;
    if(pHArray[0]<pHArray[1]){
        min = pHArray[0];max=pHArray[1];
    }
    else{
        min=pHArray[1];max=pHArray[0];
    }
    for(i=2;i<20;i++){
        if(pHArray[i]<min){
            amount+=min;        //pHArray<min
            min=pHArray[i];
        }else {
            if(pHArray[i]>max){
                amount+=max;    //pHArray>max
                max=pHArray[i];
            }else{
                amount+=pHArray[i]; //min<=pHArray<=max
            }
        }//if
    }//for
    avg = (double)amount/(20-2);
    return avg;
}

